<?php
declare(strict_types=1);
namespace app\admin\controller;
use aphp\core\Jump;
use aphp\core\Tool;

// 配置管理
class Config
{
    use Jump;

    protected string $middleware = 'rbac';

    // 列表
    public function index()
    {

        return view();
    }

    // 存储配置
    public function save_config(int $group_id, array $req)
    {
        unset($req['group_id'], $req['file']); // 删除无用参数
        $config = db('config');
        $i = 0;
        foreach ($req as $c_name => $c_value) {
            $r = $config->where('group_id', $group_id)->where('field_name', $c_name)->setField('field_value', $c_value);
            if ($r) $i++;
        }
        if ($i > 0) {
            $this->_auto_save_file($group_id); // 自动存储文件
        }
        $this->_jump(['成功存储 ' . $i . ' 项配置', '配置未改变'], $i, 'index');
    }

    // 添加
    public function add(array $req)
    {
        if ($this->isPost()) {
            $r = db()->trans(function() use ($req) {
                model('config')->save($req);
            });
            if ($r) {
                $this->_auto_save_file(intval($req['group_id'])); // 自动存储文件
            }
            $this->_jump(['添加成功', '添加失败'], $r, 'index');
        }
        $this->error('非法请求');
    }

    // 删除
    public function del(int $id)
    {
        $model = model('config')->find($id);
        $group_id = $model->group_id;
        $r = $model->del();
        if ($r) {
            $this->_auto_save_file($group_id); // 自动存储文件
        }
        $this->_jump(['删除成功', '删除失败，配置禁删'], $r, 'index');
    }

    // 修改
    public function edit(int $id, array $req)    {
        $model = model('config')->find($id);
        if (!$model) {
            $this->error('配置不存在');
        }
        $group_id = $model->group_id;
        if ($this->isPost()) {
            $r = db()->trans(function() use ($model, $req) {
                $model->save($req);
            });
            if ($r) {
                $this->_auto_save_file($group_id); // 自动存储文件
            }
            $history = $req['back_url'] ?? 'index';
            $this->_jump(['修改成功', '修改失败'], $r, $history);
        }
        return view()->with('vo', $model->toArray());
    }

    // 自动存储文件
    protected function _auto_save_file(int $group_id)
    {
        $group = db('config_group')->field('app,sign')->where('id', $group_id)->find();
        $app = $group['app'] ?: '';
        $sign = $group['sign'] ?: '';
        if (!empty($app) && !empty($sign)) {
            $file = ($app == 'common') ? ROOT_PATH . '/config/'.$sign.'.php' : ROOT_PATH . '/app/'.$app.'/config/'.$sign.'.php';
            Tool::dir_init(dirname($file));
            $data = db('config')->where('group_id', $group_id)->where('status=1')->order('sort ASC,id ASC')->column('field_value', 'field_name');
            if (empty($data)) {
                file_put_contents($file, "<?php\nreturn [];");
            } else {
                $config = var_export($data, true);
                $config = stripslashes($config);
                file_put_contents($file, "<?php\nreturn " . $config . ';');
            }
        }
        widget('config_form')->reload(); //刷新缓存
    }

    // 发送测试邮件
    public function api_test_send()
    {
        $mail = config('email');
        $title = $mail['test_send_title'] ?: '测试邮件';
        $content = $mail['test_send_content'] ?: '测试内容';
        $send_email = $mail['test_send_email'] ?: '';
        if (empty($send_email)) {
            $this->error('请先配置测试邮箱');
        }
        $send_interval = max(5, intval($mail['send_interval'])); // 发送间隔最小5秒
        $now = time(); // 当前时间
        $cookie_name = md5('send_to_'.$send_email);
        $cookie_time = intval(cookie($cookie_name)); // 有效时间
        // 获取cookie
        if ($cookie_time > 0 && $cookie_time > $now) {
            $this->error('请勿频繁发送，请等待' . ($cookie_time - $now) . '秒后重新发送。');
        }
        $smtp = extend('email.smtp');
        $r = $smtp->send($send_email, $title, $content);
        if ($r) {
            cookie($cookie_name, $now + $send_interval, ['expire' => $send_interval]);
        }
        $this->_jump(['发送成功，请进入测试邮箱查看。', $smtp->getError()], $r, 'index');
    }
}